package com.chuangjiangx.member.basic.web.websocket;

import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.domain.shared.model.PayEntry;
import com.chuangjiangx.member.stored.ddd.domain.MbrPaymentConstant;
import com.chuangjiangx.member.stored.ddd.domain.stardard.MbrPaymentResult;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by zhoufushou on 2017/12/28.
 */
@Slf4j
public class MemberCodePayListener {

    @Autowired
    private MemberQuery memberQuery;
    @Autowired
    private ObjectMapper objectMapper;

    public void handleMessage(Serializable message) {
        if(null == message){return;}
        log.info("会员码支付回调事件：{}", message.toString());

        MbrPaymentResult result = JacksonUtils.toObject(objectMapper,message.toString(),MbrPaymentResult.class);
        if (result == null) {
            return;
        }
        Map<String, Object> map = new HashMap<>(32);
        /**
         * msgType
         * 1 - 付款码付款消息
         * 2 - 会员卡券核销成功消息
         * 3 - 提货码核销成功消息
         */
        map.put("msgType", "1");
        if (Objects.equals(MbrPaymentConstant.SUCCESS,result.getResultCode())) {
            PayEntry payEntry = PayEntry.getPayEntry(result.getPayType());
            map.put("status", true);
            map.put("memberId", result.getMemberId());
            map.put("payEntryText", payEntry.name);
            map.put("payType", payEntry.value);
            map.put("mobile", result.getMobile());
            map.put("score", result.getScore());
            map.put("balance", result.getAvailableBalance());
            map.put("realPayAmount", result.getRealPayFee());
            map.put("orderNumber", result.getOrderNumber());
            map.put("payTime", result.getPayTime());
        } else {
            map.put("status", false);
            map.put("err_msg", StringUtils.defaultString(result.getErrCodeDes(),"支付失败"));
        }
        try {
            MemberCodePayWebSocketHandler.sendMessageToCustomer(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
